/*
 *   Copyright (c) 2010 Sonrisa Informatikai Kft. All Rights Reserved.
 * 
 *  This software is the confidential and proprietary information of
 *  Sonrisa Informatikai Kft. ("Confidential Information").
 *  You shall not disclose such Confidential Information and shall use it only in
 *  accordance with the terms of the license agreement you entered into
 *  with Sonrisa.
 * 
 *  SONRISA MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 *  THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 *  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 *  PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SONRISA SHALL NOT BE LIABLE FOR
 *  ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 *  DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package com.zh.jbet.web.model;

import com.zh.jbet.core.entity.BaseEntity;
import com.zh.jbet.core.service.EntityService;
import com.zh.jbet.web.JBetServiceProvider;
import org.apache.wicket.model.LoadableDetachableModel;

/**
 *
 * @author sonrisa
 */
public class EntityModel<T extends BaseEntity> extends LoadableDetachableModel<T> implements IServiceableModel<T> {

    JBetServiceProvider provider;
    private Long id;

    public EntityModel(JBetServiceProvider provider) {
        this((Long)null, provider);
    }
    
    public EntityModel(Long id, JBetServiceProvider provider) {
        this.id = id;
        this.provider = provider;
    }

    public EntityModel(T object, JBetServiceProvider provider) {
        super(object);
        this.id = object.getId();
        this.provider = provider;
    }
    
    @Override
    protected T load() {
        return id != null ? getService().load(id) : getService().getDefaultInstance();
    }

    @Override
    public void save() {
        provider.getService().save(getObject());
    }

    @Override
    public void delete() {
        provider.getService().delete(getObject());
    }

    protected EntityService<T> getService() {
        return provider.getService();
    }

    @Override
    public JBetServiceProvider getServiceProvider() {
        return provider;
    }
}
